package com.zzzyh.forumsystemclient.services.impl;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class CaptchaService {

    private final StringRedisTemplate redisTemplate;

    public CaptchaService(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    // 生成带干扰线的验证码图片并返回 Base64 数据
    public String generateCaptcha() throws IOException {
        int width = 120, height = 40;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        // 设置背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);

        // 添加干扰线
        for (int i = 0; i < 5; i++) {
            g.setColor(new Color((int) (Math.random() * 0x1000000)));
            int x1 = (int) (Math.random() * width);
            int y1 = (int) (Math.random() * height);
            int x2 = (int) (Math.random() * width);
            int y2 = (int) (Math.random() * height);
            g.drawLine(x1, y1, x2, y2);
        }

        // 生成随机验证码文本
        String code = generateRandomCode(4);
        g.setColor(Color.BLACK);
        g.setFont(new Font("Arial", Font.BOLD, 24));
        g.drawString(code, 20, 28);

        // 存储到 Redis
        String uuid = UUID.randomUUID().toString();
        String key = "captcha:" + uuid;
        redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);

        // 返回 Base64 图片
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        return "data:image/png;base64," + Base64.getEncoder().encodeToString(baos.toByteArray()) + "?uuid=" + uuid;
    }

    // 校验验证码是否正确
public boolean validateCaptcha(String uuid, String userInput) {
    String key = "captcha:" + uuid;
    String correctCode = redisTemplate.opsForValue().get(key);
    if (correctCode == null) return false;
    return correctCode.toLowerCase().equals(userInput.toLowerCase());
}


    // 生成随机字母数字组合
    private String generateRandomCode(int length) {
        StringBuilder sb = new StringBuilder();
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt((int) (Math.random() * chars.length())));
        }
        return sb.toString();
    }
}
